/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.dictionary;

import com.google.common.base.Strings;
import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.controller.CommonTreeController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.dd.DicCache;
import com.je.meta.cache.dd.DicInfoCache;
import com.je.meta.cache.dd.DicQuickCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 数据字典项左侧树
 * /je/common/tree
 */
@RestController
@RequestMapping(value = "/je/meta/dictionaryItem/tree")
public class DictionaryItemTreeController extends CommonTreeController {

    @Autowired
    private BeanService beanService;
    @Autowired
    private DicInfoCache dicInfoCache;
    @Autowired
    private DicCache dicCache;
    @Autowired
    private DicQuickCache dicQuickCache;
    /**
     * 数据字典左侧树删除
     *
     * @param param
     */
    @Override
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();

        String[] idsSplit = ids.split(",");

        List<DynaBean> items = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder()
                .ne("SY_NODETYPE", "ROOT")
                .ne("SY_PARENT", "").in("JE_CORE_DICTIONARYITEM_ID", Arrays.asList(idsSplit)));

        List<String> pathList = new ArrayList<>();
        String dictionaryId = "";
        for (DynaBean item : items) {
            if (Strings.isNullOrEmpty(dictionaryId)) {
                dictionaryId = item.getStr("DICTIONARYITEM_DICTIONARY_ID");
            }
            pathList.add(item.getStr("SY_PATH"));
        }

        int num = 0;
        for (String path : pathList) {
            int i = metaService.executeSql("delete from JE_CORE_DICTIONARYITEM where SY_PATH like '" + path + "%'");
            num = num + i;
        }
        String dicCode = getDicCode(dictionaryId);
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (StringUtil.isNotEmpty(dicCode)) {
            for (String dc : dicCode.split(",")) {
                dicCache.removeCache(dc);
                dicInfoCache.removeCache(dc);
                dicQuickCache.removeCache(dc);
                dicCache.removeCache(currentTenantId,dc);
            }
        } else {
            dicCache.clear();
            dicInfoCache.clear();
            dicQuickCache.clear();
        }
        return BaseRespResult.successResult(String.format("%s 条记录被删除", num));
    }

    @Override
    @AuthCheckPermission(value = "pc-func-JE_CORE_DICTIONARYITEM-show")
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        BaseRespResult baseRespResult = super.doUpdateList(param, request);
        List<DynaBean> lists = beanService.buildUpdateList(param.getStrData(), param.getTableCode());
        String dictionaryId = "";
        String dictionaryItemId = "";
        for (DynaBean bean : lists) {
            String action = bean.getStr("__action__");
            if ("doInsert".equals(action)) {
                dictionaryId = bean.getStr("DICTIONARYITEM_DICTIONARY_ID");
                break;
            } else {
                dictionaryItemId = bean.getStr("JE_CORE_DICTIONARYITEM_ID");
                break;
            }
        }
        String ddCode = "";
        if (!Strings.isNullOrEmpty(dictionaryId)) {
            ddCode = getDicCode(dictionaryId);
        }else {
            if (!Strings.isNullOrEmpty(dictionaryItemId)) {
                DynaBean dynaBean = metaService.selectOne("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder().eq("JE_CORE_DICTIONARYITEM_ID", dictionaryItemId));
                dictionaryId = dynaBean.getStr("DICTIONARYITEM_DICTIONARY_ID");
                ddCode = getDicCode(dictionaryId);
            }
        }
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (StringUtil.isNotEmpty(ddCode)) {
            for (String dc : ddCode.split(",")) {
                dicCache.removeCache(dc);
                dicInfoCache.removeCache(dc);
                dicQuickCache.removeCache(dc);
                dicCache.removeCache(currentTenantId,dc);
            }
        } else {
            dicCache.clear();
            dicInfoCache.clear();
            dicQuickCache.clear();
        }
        return baseRespResult;
    }

    private String getDicCode(String dictionaryId) {
        DynaBean dynaBean = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("JE_CORE_DICTIONARY_ID", dictionaryId));
        if (dynaBean != null) {
            return dynaBean.getStr("DICTIONARY_DDCODE");
        }
        return "";
    }
}
